package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetmealService setmealService;

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //1. 保存菜品的基本信息到菜品表dish
        save(dishDto);
        //2. 设置菜品与口味的关系
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(flavor -> flavor.setDishId(dishDto.getId()));
        //3. 保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public Page<DishDto> pageDishDto(Integer page, Integer pageSize, String name) {
        Page<DishDto> pageInfo = new Page<>(page, pageSize);
        return dishMapper.pageDishDto(pageInfo, name);
    }

    @Override
    public DishDto getByIdWithFlowers(Long id) {
        return dishMapper.getByIdWithFlowers(id);
    }

    @Override
    public void updateWithFlowers(DishDto dishDto) {
        updateById(dishDto);
        //删除原口味
        dishFlavorService.update().eq("dish_id", dishDto.getId()).remove();
        //添加新口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(flavor -> flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    @Transactional
    public void deleteByIds(Long[] ids) {
        Integer count1 = query().in("id", Arrays.asList(ids)).eq("status", 1).count();
        if (count1 > 0) {
            throw new CustomerException("有菜品正在售卖，不能删除");
        }
        Integer count2 = setmealService.query().eq("category_id", Arrays.asList(ids)).count();
        if (count2 > 0) {
            throw new CustomerException("有套餐正在售卖，不能删除");
        }
        removeByIds( Arrays.asList(ids));
        dishFlavorService.removeByIds(Arrays.asList(ids));
    }

    @Override
    public List<DishDto> listDishDto(Long categoryId, String name) {
        return dishMapper.listDishDto(categoryId,name);
    }
}


